<template>
  <div class="home">
    <div class="hero-section">
      <h1>{{ $t('home.title') }}</h1>
      <p class="subtitle">{{ $t('home.subtitle') }}</p>
      
      <div class="features">
        <div class="feature-item">
          <i class="el-icon-video-camera"></i>
          <span>{{ $t('home.features.watermark') }}</span>
        </div>
        <div class="feature-item">
          <i class="el-icon-video-play"></i>
          <span>{{ $t('home.features.quality') }}</span>
        </div>
        <div class="feature-item">
          <i class="el-icon-lightning"></i>
          <span>{{ $t('home.features.speed') }}</span>
        </div>
      </div>

      <div class="download-form">
        <el-input
          v-model="videoUrl"
          :placeholder="$t('home.enterUrl')"
          class="url-input"
          @change="handlePaste"
        >
          <el-button
            slot="append"
            type="primary"
            @click="handleParse"
            :loading="loading"
          >
            {{ $t('home.parse') }}
          </el-button>
        </el-input>
      </div>

      <!-- 视频解析结果展示 -->
      <div v-if="videoInfo" class="video-result">
        <div class="video-preview">
          <div class="video-player" @click="showVideoPreview">
            <img :src="videoInfo.cover_url" :alt="videoInfo.title" class="cover-image">
            <div class="play-icon">
              <i class="el-icon-video-play"></i>
            </div>
          </div>
          <div class="video-info">
            <div class="video-title">{{ videoInfo.title }}</div>
            <div class="video-meta">
              <div class="meta-item" v-if="videoInfo.author.name">
                <i class="el-icon-user"></i>
                <span>{{ videoInfo.author.name }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-time"></i>
                <span>{{ $t('home.parseTime') }}: {{ parseTime }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="video-quality-list">
          <div class="quality-title">{{ $t('home.selectQuality') }}</div>
          <el-radio-group v-model="selectedQuality" class="quality-options">
            <el-radio 
              v-for="item in videoInfo.videoDefList" 
              :key="item.videoDef"
              :label="item.url"
              class="quality-item"
            >
              <div class="quality-info">
                <span class="quality-name">{{ item.videoDef }}</span>
                <span class="quality-size">{{ item.size }}MB</span>
              </div>
            </el-radio>
          </el-radio-group>
          
          <div class="download-options">
            <el-button 
              type="primary" 
              class="download-btn"
              @click="handleDownload"
              :loading="downloading"
            >
              <i class="el-icon-download"></i>
              {{ $t('home.download') }}
            </el-button>
            <el-button 
              type="success" 
              class="preview-btn"
              @click="showVideoPreview"
            >
              <i class="el-icon-video-play"></i>
              {{ $t('home.preview') }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 视频预览弹窗 -->
      <el-dialog
        :title="$t('home.videoPreview')"
        :visible.sync="previewVisible"
        width="80%"
        :before-close="handlePreviewClose"
        class="video-preview-dialog"
      >
        <div class="preview-container">
          <video
            v-if="selectedQuality"
            :src="selectedQuality"
            controls
            class="preview-video"
            @error="handleVideoError"
          ></video>
          <div v-else class="preview-placeholder">
            {{ $t('home.selectQualityFirst') }}
          </div>
        </div>
      </el-dialog>

      <div class="supported-platforms">
        <h3>{{ $t('home.supportedPlatforms') }}</h3>
        <div class="platform-grid">
          <div
            v-for="platform in supportedPlatforms"
            :key="platform.name"
            class="platform-item"
          >
            <i :class="['platform-icon', platform.icon]"></i>
            <span>{{ platform.name }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'Home',
  data() {
    return {
      videoUrl: '',
      loading: false,
      downloading: false,
      videoInfo: null,
      selectedQuality: '',
      previewVisible: false,
      parseTime: ''
    }
  },
  computed: {
    ...mapState(['supportedPlatforms'])
  },
  methods: {
    handlePaste(inputText) {
      const urlRegex = /(https?:\/\/[^\s]+)/g
      const matches = inputText.match(urlRegex)
      console.log(matches)
      
      if (matches && matches.length > 0) {
        // 获取第一个匹配的URL
        const extractedUrl = matches[0]
        // 移除URL末尾可能存在的标点符号
        this.videoUrl = extractedUrl.replace(/[.,;:!?]$/, '')
      }
    },
    async handleParse() {
      if (!this.videoUrl) {
        this.$message.warning(this.$t('home.pleaseEnterUrl'))
        return
      }
      
      this.loading = true
      try {
        const response = await fetch(`/api/video/share/url/parse?url=${encodeURIComponent(this.videoUrl)}`)
        const data = await response.json()
        
        if (data.code === 200) {
          this.$message.success(this.$t('home.parseSuccess'))
          this.videoInfo = data.data
          // 默认选择最高质量的视频
          if (this.videoInfo.videoDefList && this.videoInfo.videoDefList.length > 0) {
            this.selectedQuality = this.videoInfo.videoDefList[0].url
          }
          // 记录解析时间
          this.parseTime = new Date().toLocaleString()
        } else {
          this.$message.error(data.msg || this.$t('home.parseFailed'))
        }
      } catch (error) {
        console.error('解析错误:', error)
        this.$message.error(this.$t('home.parseError'))
      } finally {
        this.loading = false
      }
    },
    async handleDownload() {
      if (!this.selectedQuality) {
        this.$message.warning(this.$t('home.pleaseSelectQuality'))
        return
      }

      this.downloading = true
      try {
        // 使用 fetch 下载视频
        const response = await fetch(this.selectedQuality)
        const reader = response.body.getReader()
        const contentLength = +response.headers.get('Content-Length')

        // 创建 Blob 流
        let receivedLength = 0
        const chunks = []
        let downloadStartTime = Date.now()

        // 使用 while 循环读取数据流
        while (receivedLength < contentLength) {
          const {done, value} = await reader.read()

          if (done) {
            break
          }

          chunks.push(value)
          receivedLength += value.length

          // 计算下载进度和速度
          const progress = Math.round((receivedLength / contentLength) * 100)
          const elapsedTime = (Date.now() - downloadStartTime) / 1000 // 转换为秒
          const downloadSpeed = receivedLength / elapsedTime // 字节/秒
          const speedText = this.formatSpeed(downloadSpeed)
          const progressText = this.formatProgress(receivedLength, contentLength)

          this.$message({
            message: `${this.$t('home.downloadProgress')}: ${progress}% (${progressText}) - ${speedText}`,
            type: 'info',
            duration: 0,
            showClose: true
          })
        }

        // 合并数据块
        const blob = new Blob(chunks)
        const url = window.URL.createObjectURL(blob)
        
        // 创建下载链接
        const link = document.createElement('a')
        link.href = url
        link.download = `${this.videoInfo.title}.mp4`
        document.body.appendChild(link)
        link.click()
        
        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$message.success(this.$t('home.downloadStarted'))
      } catch (error) {
        console.error('下载错误:', error)
        this.$message.error(this.$t('home.downloadError'))
      } finally {
        this.downloading = false
      }
    },
    // 格式化下载速度
    formatSpeed(bytesPerSecond) {
      const units = ['B/s', 'KB/s', 'MB/s', 'GB/s']
      let speed = bytesPerSecond
      let unitIndex = 0

      while (speed >= 1024 && unitIndex < units.length - 1) {
        speed /= 1024
        unitIndex++
      }

      return `${speed.toFixed(2)} ${units[unitIndex]}`
    },
    // 格式化下载进度
    formatProgress(received, total) {
      const units = ['B', 'KB', 'MB', 'GB']
      let receivedSize = received
      let totalSize = total
      let unitIndex = 0

      while (totalSize >= 1024 && unitIndex < units.length - 1) {
        receivedSize /= 1024
        totalSize /= 1024
        unitIndex++
      }

      return `${receivedSize.toFixed(2)}/${totalSize.toFixed(2)} ${units[unitIndex]}`
    },
    showVideoPreview() {
      if (!this.selectedQuality) {
        this.$message.warning(this.$t('home.pleaseSelectQuality'))
        return
      }
      this.previewVisible = true
    },
    handlePreviewClose(done) {
      // 停止视频播放
      const video = document.querySelector('.preview-video')
      if (video) {
        video.pause()
      }
      done()
    },
    handleVideoError() {
      this.$message.error(this.$t('home.previewError'))
      this.previewVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  .hero-section {
    max-width: 800px;
    margin: 0 auto;
    text-align: center;
    padding: 40px 20px;

    h1 {
      font-size: 2.5em;
      margin-bottom: 20px;
      color: #333;
    }

    .subtitle {
      font-size: 1.2em;
      color: #666;
      margin-bottom: 40px;
    }
  }

  .features {
    display: flex;
    justify-content: center;
    gap: 40px;
    margin-bottom: 40px;

    .feature-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      i {
        font-size: 2em;
        color: #409EFF;
        margin-bottom: 10px;
      }
    }
  }

  .download-form {
    max-width: 600px;
    margin: 0 auto 40px;

    .url-input {
      width: 100%;
    }
  }

  .video-result {
    max-width: 600px;
    margin: 0 auto 40px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .video-preview {
      margin-bottom: 20px;

      .video-player {
        position: relative;
        cursor: pointer;
        border-radius: 4px;
        overflow: hidden;
        transition: all 0.3s;

        &:hover {
          .play-icon {
            transform: scale(1.1);
            background-color: rgba(0, 0, 0, 0.7);
          }
        }

        .cover-image {
          width: 100%;
          max-height: 300px;
          object-fit: cover;
          border-radius: 4px;
        }

        .play-icon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 60px;
          height: 60px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s;

          i {
            font-size: 30px;
            color: #fff;
          }
        }
      }

      .video-info {
        text-align: left;
        margin-top: 15px;

        .video-title {
          font-size: 1.1em;
          color: #333;
          margin-bottom: 10px;
          line-height: 1.4;
        }

        .video-meta {
          display: flex;
          gap: 20px;
          color: #666;
          font-size: 0.9em;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 5px;

            i {
              font-size: 1.1em;
            }
          }
        }
      }
    }

    .video-quality-list {
      text-align: left;

      .quality-title {
        font-size: 1.1em;
        color: #333;
        margin-bottom: 15px;
      }

      .quality-options {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-bottom: 20px;

        .quality-item {
          margin-right: 0;
          padding: 10px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          transition: all 0.3s;

          &:hover {
            background-color: #f5f7fa;
          }

          .quality-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .quality-name {
              font-weight: 500;
            }

            .quality-size {
              color: #666;
              font-size: 0.9em;
            }
          }
        }
      }

      .download-options {
        display: flex;
        gap: 10px;

        .download-btn, .preview-btn {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 5px;
        }
      }
    }
  }

  .video-preview-dialog {
    .preview-container {
      width: 100%;
      background: #000;
      border-radius: 4px;
      overflow: hidden;

      .preview-video {
        width: 100%;
        max-height: 70vh;
      }

      .preview-placeholder {
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
        font-size: 1.1em;
      }
    }
  }

  .supported-platforms {
    h3 {
      margin-bottom: 20px;
    }

    .platform-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 20px;
      max-width: 600px;
      margin: 0 auto;

      .platform-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 15px;
        border: 1px solid #eee;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        i {
          font-size: 2em;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style> 